/**
 * #### 字符串统计
 * @see https://www.bilibili.com/video/BV1pu4y1n7WN?spm_id_from=333.788.videopod.sections&vd_source=9efadbd9bd76b9c14f9589f260a0c1ac
 * @category String
 * @param str 字符串
 * @returns object
 * @example
 * ```ts
 * strStatistics('abcabcabc') // {a: 3, b: 3, c: 3}
 * ```
 */
export function strStatistics(str: string) {
  return [...str].reduce((r, c) => (r[c]++ || (r[c] = 1), r), {});
}

/**
 * #### 回文字符串判断
 * @see https://www.bilibili.com/video/BV1pu4y1n7WN?spm_id_from=333.788.videopod.sections&vd_source=9efadbd9bd76b9c14f9589f260a0c1ac
 * @category String
 * @param str 字符串
 * @returns
 * @example
 * ```ts
 * isPalindrome('abcba') // true
 * ```
 */
export function isPalindrome(str: string) {
  let l = 0,
    r = str.length - 1;
  const isValid = (c: string) =>
    (c >= "a" && c <= "z") || (c >= "0" && c <= "9");
  while (l <= r) {
    const left = str[l].toLowerCase(),
      right = str[r].toLowerCase();
    if (!isValid(left)) {
      l++;
    } else if (!isValid(right)) {
      r--;
    } else if (left === right) {
      l++;
      r--;
    } else {
      return false;
    }
  }
  return true;
}
